package com.hxzy.controller.hashcart;

import com.hxzy.common.resp.R;
import com.hxzy.controller.hashcart.req.CartReq;
import com.hxzy.controller.hashcart.resp.CartResp;
import com.hxzy.controller.hashcart.resp.CartUserResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.xml.transform.Result;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @Author wy
 * @Description TODO
 * @Date 2023/9/12 9:12
 * @Version 1.0
 */
@RestController
@RequestMapping(value = "/redis/cart")
public class CartController {

    //redis  hash 存储    key=cart:用户id:商家id     字段   产品id(productId)    json{    产品数量(num)}

    @Autowired
    private RedisTemplate redisTemplate;

    /* 测试脚本
    POST http://localhost:18080/redis/cart/change
    Content-Type: application/json

    {
      "userId": 200,
      "merchantId": 100,
      "productId": 26,
      "num": 1,
      "changeType": 1
    }
     */
    /**
     * 更改购物的信息（添加商品，修改商品，删除商品）
     * @param req
     * @return
     */
    @PostMapping(value = "/change")
    public R changeCartNum(@RequestBody CartReq req){
        String redisKey="cart:"+req.getUserId()+":"+req.getMerchantId();
        //商品信息
        Object redisValue= this.redisTemplate.opsForHash().get(redisKey,  req.getProductId()+"");
        //有商品
        if(redisValue!=null){
            CartResp cartResp = (CartResp)redisValue;
            // 1 增加 -1减少"
            if(req.getChangeType()==1){
                cartResp.setNum(cartResp.getNum()+ req.getNum());
                //更新缓存
                this.redisTemplate.opsForHash().put(redisKey,req.getProductId()+"",cartResp);
            }else{
                //减少
                if(cartResp.getNum()==1 || req.getNum()>=cartResp.getNum()){
                    //删除购物车缓存
                    this.redisTemplate.opsForHash().delete(redisKey, req.getProductId()+"");
                }else{
                    cartResp.setNum(cartResp.getNum()- req.getNum());
                    //更新缓存
                    this.redisTemplate.opsForHash().put(redisKey,req.getProductId()+"",cartResp);
                }
            }
        }else{
            //新增一笔数据
            CartResp newCart=new CartResp();
            newCart.setNum(req.getNum());
            newCart.setProductId(req.getProductId());
            //查询数据库
            //newCart.setUrl("查询数据库");
            newCart.setMerchantId(req.getMerchantId());
            this.redisTemplate.opsForHash().put(redisKey,req.getProductId()+"",newCart);
        }
        return R.ok();
    }




    /**
     * GET http://localhost:18080/redis/cart/200
     * 获取用户所有购物车
     * @param userId
     * @return
     */
    @GetMapping(value = "/{userId}")
    public R findRedisCartByUserId(@PathVariable(value = "userId") Integer userId){

        List<CartUserResp> cartUserRespList=new ArrayList<>();
        //匹配用户购物车,所有商家  cart:用户id:商家id
        String redisKey="cart:"+userId+":*";
        //redis的 keys操作， 在数量比较小的时候速度快，但是占用内存的
        Set keys = this.redisTemplate.keys(redisKey);


        //用户id   商家ID   List<CartResp>
        for(Object key : keys){
            //cart:用户id:商家id
            String redisHashKey=key.toString();
            Set productSet = this.redisTemplate.opsForHash().keys(key.toString());
            //创建实体,返回给前端
            if(productSet!=null && productSet.size()>0){
                CartUserResp  cartUserResp=new CartUserResp();
                cartUserResp.setUserId(userId);
                String sjid=redisHashKey.substring(redisHashKey.lastIndexOf(":")+1);
                cartUserResp.setMerchantId(Integer.valueOf(sjid));

                List<CartResp>  respList=new ArrayList<>();
                //获取用户商品信息
                for(Object productKey : productSet){
                    //商品信息
                    CartResp cartResp = (CartResp) this.redisTemplate.opsForHash().get(key.toString(),productKey.toString() );
                    cartResp.setProductId(Integer.parseInt(productKey.toString()));
                    respList.add(cartResp);
                }
                //当前用户某个商店商品
                cartUserResp.setCartList(respList);

                //用户购物车
                cartUserRespList.add(cartUserResp);
            }
        }
        return  R.okHasData(cartUserRespList);
    }


    /**
     * 获取用户指定商家的购物车
     * @param userId
     * @return
     */
    @GetMapping(value = "/user/{userId}/merchant/{merchantId}")
    public R findRedisCartByUserIdAndMerchantId(@PathVariable(value = "userId")Integer userId,@PathVariable(value = "merchantId") Integer merchantId){

        List< CartUserResp>  cartUserRespList=new ArrayList<>();

        //key=cart:用户id:商家id
        String redisKey="cart:"+userId+":"+merchantId;
        //用户商品所有的键
        Set productSet = this.redisTemplate.opsForHash().keys(redisKey);

        //创建实体,返回给前端
        if(productSet!=null && productSet.size()>0){
            CartUserResp  cartUserResp=new CartUserResp();
            cartUserResp.setUserId(userId);
            cartUserResp.setMerchantId( merchantId);

            List<CartResp>  respList=new ArrayList<>();
            //获取用户商品信息
            for(Object productKey : productSet){
                //商品信息
                CartResp cartResp = (CartResp) this.redisTemplate.opsForHash().get(redisKey  ,productKey.toString() );
                cartResp.setProductId(Integer.parseInt(productKey.toString()));
                respList.add(cartResp);
            }
            //当前用户某个商店商品
            cartUserResp.setCartList(respList);

            //用户购物车
            cartUserRespList.add(cartUserResp);
        }

        return  R.okHasData(cartUserRespList);
    }


}
